<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus"
import { useComboStore } from "@/store/modules/combo"
import {
  getconfigurationRuleApi,
  getconfigurationRuleApiAdd,
  getconfigurationRuleApiUpdate,
  getconfigurationRuleApiDel
} from "@/api/configurationRule"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const loading = ref<boolean>(false)
const comboStore = useComboStore()
//#region 增
const dialogVisible = ref<boolean>(false)
const formData = reactive<any>({
  package_id: "", // 套餐id
  cash_own: "", // 自己佣金
  cash_super: "", // 上级佣金
  cash_upup: "", //  上上级佣金
  cash_money: "" //  首冲限制返佣
})
const formRules: FormRules = reactive({
  package_id: [{ required: true, trigger: "change", message: "请选择套餐" }],
  cash_own: [
    { required: true, trigger: "blur", message: "请输入自己佣金" },
    { pattern: /^[0-9]*[1-9][0-9]*$/, message: "只能输入正整数", trigger: "blur" }
  ],
  cash_super: [
    { required: true, trigger: "blur", message: "请输入上级佣金" },
    { pattern: /^[0-9]*[1-9][0-9]*$/, message: "只能输入正整数", trigger: "blur" }
  ],
  cash_upup: [
    { required: true, trigger: "blur", message: "请输入上上级佣金" },
    { pattern: /^[0-9]*[1-9][0-9]*$/, message: "只能输入正整数", trigger: "blur" }
  ],
  cash_money: [
    { required: true, trigger: "blur", message: "请输入返佣条件" },
    { pattern: /^[0-9]*[1-9][0-9]*$/, message: "只能输入正整数", trigger: "blur" }
  ]
})

const comboList = ref<any>([]) // 套餐列表
/**监听套餐缓存(pinia) */
comboStore.getComoboFn()
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        getconfigurationRuleApiAdd(formData, true).then(() => {
          ElMessage.success("新增成功")
          console.log(formData, "获取表单数据")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        getconfigurationRuleApiUpdate(
          {
            package_id: formData.package_id,
            cash_own: formData.cash_own,
            cash_super: formData.cash_super,
            cash_upup: formData.cash_upup,
            cash_money: formData.cash_money
          },
          true
        ).then(() => {
          ElMessage.success("修改成功")
          console.log("修改")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除此套餐配置规则？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    console.log(row.package_id)
    getconfigurationRuleApiDel(row.package_id, true).then(() => {
      // ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  console.log(row)
  dialogVisible.value = true
  currentUpdateId.value = row.package_id
  formData.package_id = row.package_id
  formData.cash_own = row.cash_own
  formData.cash_super = row.cash_super
  formData.cash_upup = row.cash_upup
  formData.cash_money = row.cash_money
}
//#endregion

//#region 查
const tableData = ref<any>([])
const getTableData = () => {
  loading.value = true
  getconfigurationRuleApi(
    {
      page: paginationData.currentPage,
      size: paginationData.pageSize
    },
    true
  )
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
      console.log(res, "查询的数据")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    // console.log(item, "过滤")
    if (item.id == row.package_id) {
      celValue = item.name
    }
  })
  return celValue
}
// 刷新数据
const handleRefresh = () => {
  getTableData()
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
//#endregion

// #region 清除验证  清除规则报错信息
const formRef = ref<FormInstance | null>(null)
const clearValidateA = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidateA()
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key]
  })
}
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加佣金规则</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          {{ tableData }}
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column type="index" label="序号" width="120" align="center">
            <template #default="{ $index }">
              {{ (paginationData.currentPage - 1) * paginationData.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="package_id" label="套餐名" align="center" /> -->
          <el-table-column
            prop="package_id"
            label="套餐"
            align="center"
            :formatter="formatterCombo"
            show-overflow-tooltip
          />
          <el-table-column prop="cash_own" label="自主佣金(元)" align="center" />
          <el-table-column prop="cash_super" label="上级佣金(元)" align="center" />
          <el-table-column prop="cash_upup" label="上上级佣金(元)" align="center" />
          <el-table-column prop="cash_money" label="首冲限制返佣(元)" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增 修改-->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="38%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
        :inline="true"
      >
        <el-form-item prop="package_id" label="套餐名">
          <el-select v-model="formData.package_id" clearable placeholder="请选套餐">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="cash_own" label="自己佣金">
          <el-input v-model="formData.cash_own" placeholder="请输入自己佣金" />
        </el-form-item>
        <el-form-item prop="cash_super" label="上级佣金">
          <el-input v-model="formData.cash_super" placeholder="请输入上级佣金" />
        </el-form-item>
        <el-form-item prop="cash_upup" label="上上级佣金">
          <el-input v-model="formData.cash_upup" placeholder="请输入上上级佣金" />
        </el-form-item>
        <el-form-item prop="cash_money" label="首冲限制返佣">
          <el-input v-model="formData.cash_money" placeholder="请输入首冲限制" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
// input 输入框长度
:deep(.el-input__wrapper) {
  width: 180px;
}
:deep(.el-form-item__label) {
  padding: 0px;
}
</style>
